package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.InputFilter
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.BloodLineDictionaryResponse
import com.gexiaobao.pigeon.app.model.bean.BreedCategoryBean
import com.gexiaobao.pigeon.app.model.bean.BreedCategoryResponse
import com.gexiaobao.pigeon.app.model.bean.BreedStatusList
import com.gexiaobao.pigeon.app.model.bean.BreedStatusResponse
import com.gexiaobao.pigeon.app.model.bean.BreedingPigeonDetailResponse
import com.gexiaobao.pigeon.app.model.bean.ImageListBean
import com.gexiaobao.pigeon.app.model.bean.ListCountryBean
import com.gexiaobao.pigeon.app.model.bean.PgBloodListBean
import com.gexiaobao.pigeon.app.model.bean.PgBloodResponse
import com.gexiaobao.pigeon.app.model.bean.PgEyeBean
import com.gexiaobao.pigeon.app.model.bean.PgEyeResponse
import com.gexiaobao.pigeon.app.model.bean.PgFeatherColorBean
import com.gexiaobao.pigeon.app.model.bean.PgFeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.PgSourceResponse
import com.gexiaobao.pigeon.app.model.bean.UiState
import com.gexiaobao.pigeon.app.model.param.AddBloodPigeonParam
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.TransInformation
import com.gexiaobao.pigeon.databinding.ActivityAddBloodPigeonBinding
import com.gexiaobao.pigeon.ui.adapter.AddBloodPigeonPopAdapter
import com.gexiaobao.pigeon.ui.adapter.UploadImageAdapter
import com.gexiaobao.pigeon.ui.dialog.RxInputCustomDialog
import com.gexiaobao.pigeon.ui.view.recycleview.FullyGridLayoutManager
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DensityUtil
import com.luck.picture.lib.utils.MediaUtils
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.bean.ErrorBean
import com.zs.easy.imgcompress.listener.OnCompressMultiplePicsListener
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.finish
import me.hgj.jetpackmvvm.util.startActivityForResult
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.util.Calendar


/**
 * @Author      : hxw
 * @Date        : 2024/8/20 13:33
 * @Describe    : 添加种鸽
 */
class ActivityAddBloodPigeon : BaseActivity<BreedingPigeonViewModel, ActivityAddBloodPigeonBinding>() {

    private var mType = 0//1-添加，2-编辑,3-作育(修改种鸽信息)
    private var mId = 0
    private var pigeonSex = ""
    private var imageIds: ArrayList<Int> = arrayListOf()
    private var editPhotoFlag = 0
    private var addPhotoFlag = 1
    private var isAmend = false//true-可编辑性别，false-不可编辑性别
    private var mListImageBean: ArrayList<ImageListBean> = arrayListOf()
    private val mDataLocalResult: MutableList<LocalMedia> = arrayListOf()

    private val maxSelectNum = 6
    private val mAdapter: UploadImageAdapter by lazy { UploadImageAdapter(this, arrayListOf()) }
    private lateinit var pop: PopupWindow
    private var pictureResult: ArrayList<LocalMedia> = arrayListOf()

    //选取年国家/地区
    private var adapterCountry: AddBloodPigeonPopAdapter? = null
    private val mCountryList: ArrayList<String> = arrayListOf()
    private val popWindowCountry: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var countryList: ArrayList<ListCountryBean> = arrayListOf()
    private var country = ""
    private var countryEn = ""
    private var mPositionCountry = 2

    //选取年份
    private var adapterYear: AddBloodPigeonPopAdapter? = null
    private var mYearList: MutableList<String> = arrayListOf()
    private val popWindowYear: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mYearPosition = 1

    //状态
    private var adapterStatus: AddBloodPigeonPopAdapter? = null
    private var mStatusList: MutableList<String> = arrayListOf()
    private var statusList: MutableList<BreedStatusList> = arrayListOf()
    private val popWindowStatus: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mStatusPosition = 0

    //类别
    private var adapterCategory: AddBloodPigeonPopAdapter? = null
    private var mCategoryList: MutableList<String> = arrayListOf()
    private var categoryList: MutableList<BreedCategoryBean> = arrayListOf()
    private val popWindowCategory: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mCategoryPosition = 0

    //羽色
    private var adapterColor: AddBloodPigeonPopAdapter? = null
    private var mColorList: MutableList<String> = arrayListOf()
    private var colorList: MutableList<PgFeatherColorBean> = arrayListOf()
    private val popWindowColor: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mColorPosition = 0

    //眼砂
    private var adapterEye: AddBloodPigeonPopAdapter? = null
    private var mListEye: MutableList<String> = arrayListOf()
    private var eyeList: MutableList<PgEyeBean> = arrayListOf()
    private val popWindowEye: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mPositionEye = 0

    //血统
    private var adapterBlood: AddBloodPigeonPopAdapter? = null
    private var mListBlood: MutableList<String> = arrayListOf()
    private var bloodList: MutableList<PgBloodListBean> = arrayListOf()
    private val popWindowBlood: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mPositionBlood = 0

    //来源
    private var adapterSource: AddBloodPigeonPopAdapter? = null
    private var mListSource: MutableList<String> = arrayListOf()
    private val popWindowSource: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mPositionSource = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        pigeonSex = getString(R.string.hint_unknown)
        // 获取屏幕高度
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenHeight = displayMetrics.heightPixels
//        // 监听软键盘状态
//        mDatabind.llRootLayout.viewTreeObserver.addOnGlobalLayoutListener {
//            val r = Rect()
//            mDatabind.llRootLayout.getWindowVisibleDisplayFrame(r)
//            /** 计算高度差 */
//            val heightDiff = mDatabind.llRootLayout.height - (r.bottom - r.top)
//            if (heightDiff > screenHeight / 4) {
//                // 软键盘弹出，界面上移
//                mDatabind.llRootLayout.scrollTo(0, heightDiff + 90)
//            } else {
//                // 软键盘收起，界面下移
//                mDatabind.llRootLayout.scrollTo(0, 0)
//            }
//        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "添加种鸽"
        mDatabind.tvUnKnow.isSelected = true
        mDatabind.tvCountryNameEn.transformationMethod = TransInformation()

        mType = intent.getIntExtra("type", 0)
        if (mType == 2 || mType == 3) {
            val id = intent.getIntExtra("id", 0)
            showLoading(getString(R.string.loading))
            mViewModel.getBreedingPigeonInfo(id.toString())
        }

        isAmend = intent.getBooleanExtra("isAmend", false)

        initListener()
        initAdapter()
        /** 创建一个 InputFilter */
        val filter = InputFilter { source, _, _, _, _, _ ->
            val allowedCharacters = "^[a-zA-Z0-9]*$"
            if (source != null && !source.matches(allowedCharacters.toRegex())) {
                ""
                /** 不允许输入不匹配的字符 */
            } else {
                null
                /** 允许输入的字符 */
            }
        }

        /** 将 InputFilter 设置到 EditText */
        mDatabind.etRingId.filters = arrayOf(filter)
        mDatabind.etViceRingId.filters = arrayOf(filter)
        mDatabind.etAreaCode.filters = arrayOf(filter)
    }

    @SuppressLint("SetTextI18n")
    private fun showEditContent(data: BreedingPigeonDetailResponse?) {
        if (data != null) {
            mDatabind.isVisible = data.category == getString(R.string.shed)
            mDatabind.data = data
            val sex = data.sex
            mDatabind.tvUnKnow.isSelected = sex == getString(R.string.hint_unknown)
            mDatabind.llFemale.isSelected = sex == getString(R.string.hint_female)
            mDatabind.llMale.isSelected = sex == getString(R.string.hint_male)
            if (!isAmend) {
                if (sex == "雌") {
                    mDatabind.tvUnKnow.isVisible = false
                    mDatabind.llMale.isVisible = false
                    mDatabind.llFemale.isSelected = true
                } else {
                    mDatabind.tvUnKnow.isVisible = false
                    mDatabind.llFemale.isVisible = false
                    mDatabind.llMale.isSelected = true
                }
            }
        }
    }

    private fun initAdapter() {
        val manager = FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        mDatabind.recyclerImage.layoutManager = manager
        mDatabind.recyclerImage.addItemDecoration(GridSpacingItemDecoration(3, DensityUtil.dip2px(this, 5f), false))
        mAdapter.selectMax = maxSelectNum
        mDatabind.recyclerImage.adapter = mAdapter
        mAdapter.setIntentType(mType)
        mAdapter.data.clear()
        if (mType == 2 || mType == 3 && mListImageBean.isNotEmpty()) {
            mListImageBean.forEachIndexed { index, s ->
                mDataLocalResult.add(index, LocalMedia(s.url, s.id))
            }
        }
        mAdapter.data.addAll(mDataLocalResult)
        mAdapter.checkPos = if (editPhotoFlag == 0) 0 else editPhotoFlag - 1
        mAdapter.setOnItemClickListener(object : UploadImageAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                if (mType == 1) {
                    // 预览图片、视频、音频
                    PictureSelector.create(this@ActivityAddBloodPigeon)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .startActivityPreview(position, true, mAdapter.data as ArrayList<LocalMedia>?)
                } else {
                    if (mAdapter.data.isNotEmpty()) {
                        val image = arrayListOf<String>()
                        mAdapter.data.forEach {
                            image.add(it.imageUrl)
                        }
                        openAdapterBigImage(position, mDatabind.recyclerImage, image)
                    }
                }
            }

            override fun openPicture() {
                showPop()
            }

            override fun onCoverChecked(position: Int) {
                editPhotoFlag = position + 1
                addPhotoFlag = position + 1
            }

            override fun onDeleteImage(index: Int) {
                try {
                    if (mType == 1) {//添加
                        /** 如果删除的是最后一张并且选中的封面也是最后一张,则默认去选中第一张作为封面 */
                        if (index == mAdapter.data.size - 1 && addPhotoFlag - 1 == index) {
                            mAdapter.data[0].isChecked = true
                            mAdapter.checkPos = 0
                            addPhotoFlag = 1
                            mAdapter.notifyItemChanged(0)
                        } else {
                            if (index < addPhotoFlag - 1) {
                                addPhotoFlag -= 1
                                mAdapter.data[addPhotoFlag - 1].isChecked = true
                                mAdapter.checkPos = addPhotoFlag - 1
                                mAdapter.notifyItemChanged(addPhotoFlag - 1)
                            }
                        }
                    }
                    if (mType == 2) {//编辑
                        /** 如果删除的是最后一张并且选中的封面也是最后一张,则默认去选中第一张作为封面 */
                        if (index == mAdapter.data.size - 1 && editPhotoFlag - 1 == index) {
                            mAdapter.data[0].isChecked = true
                            mAdapter.checkPos = 0
                            editPhotoFlag = 1
                            mAdapter.notifyItemChanged(0)
                        } else {
                            if (index < editPhotoFlag - 1) {
                                editPhotoFlag -= 1
                                mAdapter.data[editPhotoFlag - 1].isChecked = true
                                mAdapter.checkPos = editPhotoFlag - 1
                                mAdapter.notifyItemChanged(editPhotoFlag - 1)
                            }
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
    }

    private fun showPop() {
        hideSoftKeyboard(this@ActivityAddBloodPigeon)
        val bottomView = View.inflate(this, R.layout.layout_bottom_dialog, null)
        val mAlbum = bottomView.findViewById<TextView>(R.id.tv_album)
        val mCamera = bottomView.findViewById<TextView>(R.id.tv_camera)
        val mCancel = bottomView.findViewById<TextView>(R.id.tv_cancel)

        pop = PopupWindow(bottomView, -1, -2)
        pop.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        pop.isOutsideTouchable = true
        pop.isFocusable = true
        val lp = window.attributes
        lp.alpha = 0.5f
        window.attributes = lp
        pop.setOnDismissListener {
            window.attributes.alpha = 1f
            window.attributes = lp
        }
        pop.animationStyle = R.style.main_menu_photo_anim
        pop.showAtLocation(window.decorView, Gravity.BOTTOM, 0, 0)

        @SuppressLint("NotifyDataSetChanged")
        val clickListener = View.OnClickListener { view ->
            when (view.id) {
                R.id.tv_album ->//相册
                    PictureSelector.create(this)
                        .openGallery(SelectMimeType.ofImage())
                        .setMaxSelectNum(maxSelectNum)
                        .setMinSelectNum(1)
                        .isDisplayCamera(false)//是否打开摄像按钮
                        .isMaxSelectEnabledMask(true)//是否显示蒙层（达到最大可选数量）
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setCompressEngine(PictureUtil.getCompressFileEngine())
                        .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
                        .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
                        .setImageSpanCount(3)
                        .setSelectionMode(SelectModeConfig.MULTIPLE)
                        .setSelectedData(mAdapter.data)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: ArrayList<LocalMedia>?) {
                                analyticalSelectResults(result)
                            }

                            override fun onCancel() {}
                        })

                R.id.tv_camera ->//拍照
                    PictureSelector.create(this)
                        .openCamera(SelectMimeType.ofImage())
                        .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
                        .setCompressEngine(PictureUtil.getCompressFileEngine())
                        .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
                        .setSelectedData(mAdapter.data)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: ArrayList<LocalMedia>?) {
                                analyticalSelectResults(result)
                            }

                            override fun onCancel() {}
                        })

                R.id.tv_cancel -> {
                    closePopupWindow()
                }
            }
            closePopupWindow()
        }

        mAlbum.setOnClickListener(clickListener)
        mCamera.setOnClickListener(clickListener)
        mCancel.setOnClickListener(clickListener)
    }

    private fun closePopupWindow() {
        if (::pop.isInitialized && pop.isShowing) {
            pop.dismiss()
        }
    }

    private fun analyticalSelectResults(result: ArrayList<LocalMedia>?) {
        if (result != null) {
            pictureResult.addAll(result)
            for (media in result) {
                if (media.width == 0 || media.height == 0) {
                    if (PictureMimeType.isHasImage(media.mimeType)) {
                        val imageExtraInfo = MediaUtils.getImageSize(this, media.path)
                        media.width = imageExtraInfo.width
                        media.height = imageExtraInfo.height
                    } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                        val videoExtraInfo = MediaUtils.getVideoSize(this, media.path)
                        media.width = videoExtraInfo.width
                        media.height = videoExtraInfo.height
                    }
                }
            }
            if (mType == 1) {
                runOnUiThread {
                    val isMaxSize = result.size == mAdapter.selectMax
                    val oldSize: Int = mAdapter.data.size
                    mAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
                    mAdapter.data.clear()
                    mAdapter.data.addAll(result)
                    mAdapter.notifyItemRangeInserted(0, result.size)
                }
            } else {
                mDataLocalResult.clear()
                mDataLocalResult.addAll(result)
                val list = arrayListOf<File>()
                if (result.isNotEmpty()) {
                    result.forEach {
                        if (it.realPath != null) {
                            list.add(File(it.realPath))
                        }
                    }
                    val map = hashMapOf(
                        "img" to list
                    )
                    showLoading(getString(R.string.Upload_Center))
                    mViewModel.uploadGenealogyBookImg(map)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initListener() {
        mDatabind.llMale.setOnClickListener {
            selectedPigeonSex("male")
        }
        mDatabind.llFemale.setOnClickListener {
            selectedPigeonSex("female")
        }
        mDatabind.tvUnKnow.setOnClickListener {
            selectedPigeonSex("unKnow")
        }

        popWindowCountry.setOnItemClickListener { _, _, position, _ ->
            mPositionCountry = position
            if (position != 0 && position != 1) {
                adapterCountry?.setCheckItem(position)
                countryEn = countryList[position - 2].data
                country = countryList[position - 2].name
                mDatabind.tvCountryNameEn.text = "$countryEn $country"
            } else {
                if (mCountryList[position] == "未知") {
                    mDatabind.tvCountryNameEn.text = getString(R.string.hint_unknown)
                } else {
                    showInputCustomDialog()
                }
            }
            popWindowCountry.dismiss()
        }

        popWindowYear.setOnItemClickListener { _, _, position, _ ->
            mYearPosition = position
            adapterYear?.setCheckItem(position)
            mDatabind.tvYear.text = mYearList[position]
            popWindowYear.dismiss()
        }

        popWindowStatus.setOnItemClickListener { _, _, position, _ ->
            mStatusPosition = position
            adapterStatus!!.setCheckItem(position)
            mDatabind.tvPigeonStatus.text = statusList[position].state
            popWindowStatus.dismiss()
        }

        popWindowCategory.setOnItemClickListener { _, _, position, _ ->
            mCategoryPosition = position
            val category = categoryList[position].category
            adapterCategory!!.setCheckItem(position)
            mDatabind.tvPigeonCategory.text = category
            mDatabind.llRaceSponsor.isVisible = category == "公棚"
            popWindowCategory.dismiss()
        }

        popWindowColor.setOnItemClickListener { _, _, position, _ ->
            if (position == 0) {
                startActivityForResult<ActivityAddCustom>("title" to "羽色") {
                    if (it != null) {
                        mDatabind.tvPigeonFeatherColor.text = it.getStringExtra("content")
                    }
                }
                popWindowColor.dismiss()
                return@setOnItemClickListener
            }
            mColorPosition = position
            adapterColor!!.setCheckItem(position)
            mDatabind.tvPigeonFeatherColor.text = colorList[position - 1].featherColor
            popWindowColor.dismiss()
        }

        popWindowEye.setOnItemClickListener { _, _, position, _ ->
            if (position == 0) {
                startActivityForResult<ActivityAddCustom>("title" to "眼砂") {
                    if (it != null) {
                        mDatabind.tvPigeonEyeSand.text = it.getStringExtra("content")
                    }
                }
                popWindowEye.dismiss()
                return@setOnItemClickListener
            }
            mPositionEye = position
            adapterEye!!.setCheckItem(position)
            mDatabind.tvPigeonEyeSand.text = eyeList[position - 1].eye
            popWindowEye.dismiss()
        }

        popWindowBlood.setOnItemClickListener { _, _, position, _ ->
            if (position == 0) {
                startActivityForResult<ActivityAddCustom>("title" to "血统") {
                    if (it != null) {
                        mDatabind.tvPigeonBlood.text = it.getStringExtra("content")
                    }
                }
                popWindowBlood.dismiss()
                return@setOnItemClickListener
            }
            mPositionBlood = position
            adapterBlood!!.setCheckItem(position)
            mDatabind.tvPigeonBlood.text = bloodList[position - 1].blood
            popWindowBlood.dismiss()
        }

        popWindowSource.setOnItemClickListener { _, _, position, _ ->
            mPositionSource = position
            adapterSource!!.setCheckItem(position)
            mDatabind.tvPigeonSource.text = mListSource[position]
            popWindowSource.dismiss()
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取种鸽详情 */
        mViewModel.detailResult.observe(this) {
            if (it != null) {
                mId = it.id
                pigeonSex = it.sex
                country = it.country
                countryEn = it.countryEn
                editPhotoFlag = it.photoFlag
                mDatabind.data = it
                if (it.list.isNotEmpty()) {
                    mListImageBean.clear()
                    mListImageBean.addAll(it.list)
                }
                showEditContent(it)
                initAdapter()
            }
        }
        /** 上传图片 */
        mViewModel.uploadImagesResult.observe(this) {
            if (it?.list != null && it.list.isNotEmpty()) {
                if (it.list.size != mDataLocalResult.size && mDataLocalResult.size > it.list.size) {
                    var poor = mDataLocalResult.size - it.list.size//计算两个list的元素之差
                    for (i in 0 until it.list.size) {
                        if (mDataLocalResult[poor].imageId == null) {
                            mDataLocalResult[poor] = LocalMedia(it.list[i].url, it.list[i].id)
                            poor++
                        }
                    }
                } else {
                    for (i in 0 until it.list.size) {
                        mDataLocalResult[i] = LocalMedia(it.list[i].url, it.list[i].id)
                    }
                }
            }
            val isMaxSize = mDataLocalResult.size == mAdapter.selectMax
            val oldSize: Int = mAdapter.data.size
            mAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
            mAdapter.data.clear()
            mAdapter.data.addAll(mDataLocalResult)
            mAdapter.notifyItemRangeInserted(0, mDataLocalResult.size)
        }
        /** 编辑种鸽 */
        mViewModel.editBreedingPigeonInfoResult.observe(this) {
            intentBack(it)
        }
        /** 添加种鸽 */
        mViewModel.addBreedingPigeonResult.observe(this) {
            intentBack(it)
        }
        /** 获取种鸽来源列表 */
        mViewModel.getPgSourceResult.observe(this) {
            setPgSourceList(it)
        }
        /** 获取血統列表 */
        mViewModel.getPgBloodResult.observe(this) {
            setPgBloodList(it)
        }
        /** 获取眼砂列表 */
        mViewModel.getPgEyeResult.observe(this) {
            setPgEyeList(it)
        }
        /** 获取羽色列表 */
        mViewModel.getPgFeatherColorResult.observe(this) {
            setFeatherColorList(it)
        }
        /** 获取种鸽类别  */
        mViewModel.getPgBreedCategoryResult.observe(this) {
            setCategoryList(it)
        }
        /** 获取种鸽状态  */
        mViewModel.getPgBreedStatusResult.observe(this) {
            setBreedStatusList(it)
        }
        /** 获取国家/地区列表 */
        mViewModel.getBloodLineDictionaryResult.observe(this) {
            setCountryList(it)
        }
    }

    private fun intentBack(it: UiState?) {
        if (it != null) {
            if (it.isSuccess) {
                if (mType == 3) {
                    val intent = Intent()
                    intent.putExtra("id", mId)
                    finish(intent)
                } else {
                    finish()
                    eventViewModel.toRefreshData.value = true
                }
            } else {
                RxToast.warning(it.errorMsg)
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.tvAddBloodPigeonSubmit,
            mDatabind.llCountryNameEn,
            mDatabind.llYear,
            mDatabind.llPigeonStatus,
            mDatabind.llPigeonCategory,
            mDatabind.llPigeonBirthday,
            mDatabind.llPigeonFeatherColor,
            mDatabind.llPigeonEyeSand,
            mDatabind.llPigeonBlood,
            mDatabind.llPigeonSource,
            mDatabind.tvAddBloodDescribe,
            mDatabind.tvBloodGradeDescribe
        ) {
            when (it) {
                mDatabind.tvBloodGradeDescribe -> {
                    val describe = mDatabind.tvBloodGradeDescribe.text.toString().trim()
                    startActivityForResult<ActivityEditDescribeInfo>(
                        "title" to getString(R.string.breeding_book_description),
                        "describe" to describe,
                        "type" to 2
                    ) { data ->
                        if (data != null) {
                            mDatabind.tvBloodGradeDescribe.text = data.getStringExtra("describe")
                        }
                    }
                }

                mDatabind.tvAddBloodDescribe -> {
                    val describe = mDatabind.tvAddBloodDescribe.text.toString().trim()
                    startActivityForResult<ActivityEditDescribeInfo>(
                        "title" to getString(R.string.Breeding_pigeon_data_description),
                        "describe" to describe,
                        "type" to 1
                    ) { data ->
                        if (data != null) {
                            mDatabind.tvAddBloodDescribe.text = data.getStringExtra("describe")
                        }
                    }
                }

                mDatabind.llPigeonSource -> mViewModel.getPgSource()
                mDatabind.llPigeonBlood -> mViewModel.getPgBlood(1)
                mDatabind.llPigeonEyeSand -> mViewModel.getPgEye(1)
                mDatabind.llPigeonFeatherColor -> mViewModel.getPgFeatherColor(1)
                mDatabind.llPigeonBirthday -> chooseDate()
                mDatabind.llPigeonCategory -> mViewModel.getPgBreedCategory()
                mDatabind.llPigeonStatus -> mViewModel.getPgBreedStatus()
                mDatabind.llYear -> setYearPopList()
                mDatabind.llCountryNameEn -> mViewModel.getBloodLineDictionary()
                mDatabind.includeBar.ivBack -> finish()
                mDatabind.tvAddBloodPigeonSubmit -> addBloodPigeon()
            }
        }
    }

    private fun addBloodPigeon() {
        if (mAdapter.data.isNotEmpty()) {
            imageIds.clear()
            mAdapter.data.forEach {
                if (it.imageId != null) {
                    imageIds.add(it.imageId)
                }
            }
        }
        val countryName = mDatabind.tvCountryNameEn.text.toString().trim()
        val year = mDatabind.tvYear.text.toString().trim()
        val areaCode = mDatabind.etAreaCode.text.toString().trim().ifEmpty { "00" }
        val ringId = mDatabind.etRingId.text.toString().trim()
        val subRingId = mDatabind.etViceRingId.text.toString().trim()
        val nickName = mDatabind.etNickName.text.toString().trim()
        val pigeonStatus = mDatabind.tvPigeonStatus.text.toString().trim()
        val pigeonCategory = mDatabind.tvPigeonCategory.text.toString().trim()
        val pigeonBirthday = mDatabind.tvPigeonBirthday.text.toString().trim()
        val mColor = mDatabind.tvPigeonFeatherColor.text.toString().trim()
        val mEye = mDatabind.tvPigeonEyeSand.text.toString().trim()
        val mPigeonBlood = mDatabind.tvPigeonBlood.text.toString().trim()
        val mPigeonSource = mDatabind.tvPigeonSource.text.toString().trim()
        val mPigeonDescribe = mDatabind.tvAddBloodDescribe.text.toString().trim()
        val mPigeonGradeDes = mDatabind.tvBloodGradeDescribe.text.toString().trim()
        val raceSponsor = mDatabind.etRaceSponsor.text.toString().trim()
        when {
            country.isEmpty() && countryEn.isEmpty() && countryName.isEmpty() -> showMessage(getString(R.string.Please_select_a_country))
            ringId.isEmpty() -> showMessage(getString(R.string.Please_fill_in_the_foot_ring_number))
            pigeonCategory == "公棚" && raceSponsor.isEmpty() -> showMessage(getString(R.string.input_shed_name))
            else -> {
                if (mType == 1) {
                    val imageFile: ArrayList<File> = arrayListOf()
                    val fileList: MutableList<String> = arrayListOf()
                    if (mAdapter.data.isNotEmpty()) {
                        fileList.clear()
                        mAdapter.data.forEachIndexed { _, localMedia ->
                            fileList.add(localMedia.realPath)
                        }
                    }
                    if (fileList.isEmpty()) {
                        addPhotoFlag = 0
                        val param = AddBloodPigeonParam(
                            country = country,
                            countryEn = countryEn.ifEmpty { countryName },
                            year = year,
                            area = areaCode,
                            ringId = ringId,
                            subRing = subRingId,
                            name = nickName,
                            status = pigeonStatus,
                            category = pigeonCategory,
                            sex = pigeonSex,
                            hatchedDate = pigeonBirthday,
                            featherColor = mColor,
                            eye = mEye,
                            blood = mPigeonBlood,
                            source = mPigeonSource,
                            pgDesc = mPigeonDescribe,
                            gradesDesc = mPigeonGradeDes,
                            photoFlag = addPhotoFlag,
                            loftName = raceSponsor,
                            img = imageFile,
                        )
                        showLoading(getString(R.string.loading))
                        mViewModel.addBreedingPigeon(param)
                        return
                    }
                    EasyImgCompress.withMultiPics(this, fileList)
                        .maxPx(1500)
                        .maxSize(1500)
                        .enableLog(true)
                        .setOnCompressMultiplePicsListener(object : OnCompressMultiplePicsListener {
                            override fun onStart() {
                                showLoading(getString(R.string.Picture_processing))
                            }

                            override fun onSuccess(successFiles: MutableList<File>?) {
                                dismissLoading()
                                imageFile.clear()
                                imageFile.addAll(successFiles!!)
                                val param = AddBloodPigeonParam(
                                    country = country,
                                    countryEn = countryEn.ifEmpty { countryName },
                                    year = year,
                                    area = areaCode,
                                    ringId = ringId,
                                    subRing = subRingId,
                                    name = nickName,
                                    status = pigeonStatus,
                                    category = pigeonCategory,
                                    sex = pigeonSex,
                                    hatchedDate = pigeonBirthday,
                                    featherColor = mColor,
                                    eye = mEye,
                                    blood = mPigeonBlood,
                                    source = mPigeonSource,
                                    pgDesc = mPigeonDescribe,
                                    gradesDesc = mPigeonGradeDes,
                                    photoFlag = addPhotoFlag,
                                    loftName = raceSponsor,
                                    img = imageFile,
                                )
                                showLoading(getString(R.string.loading))
                                mViewModel.addBreedingPigeon(param)
                            }

                            override fun onHasError(successFiles: MutableList<File>?, errors: MutableList<ErrorBean>?) {
                                LogUtils.debugInfo("onError error = ${errors?.size.toString()}" + successFiles?.size.toString())
                            }
                        }).start()
                } else {
                    val map = mapOf(
                        "id" to mId,
                        "country" to country,
                        "countryEn" to countryEn.ifEmpty { countryName },
                        "year" to year,
                        "area" to areaCode,
                        "ringId" to ringId,
                        "subRing" to subRingId,
                        "name" to nickName,
                        "status" to pigeonStatus,
                        "category" to pigeonCategory,
                        "sex" to pigeonSex,
                        "hatchedDate" to pigeonBirthday,
                        "featherColor" to mColor,
                        "eye" to mEye,
                        "blood" to mPigeonBlood,
                        "source" to mPigeonSource,
                        "pgDesc" to mPigeonDescribe,
                        "gradesDesc" to mPigeonGradeDes,
                        "photoFlag" to editPhotoFlag,
                        "loftName" to raceSponsor,
                        "imgs" to imageIds,
                    )
                    val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                    showLoading(getString(R.string.loading))
                    mViewModel.editBreedingPigeonInfo(body)
                }
            }
        }
    }

    private fun setPgSourceList(it: PgSourceResponse?) {
        mListSource.clear()
        if (it != null && it.list.isNotEmpty()) {
            it.list.forEach {
                mListSource.add(it)
            }
        }
        adapterSource = AddBloodPigeonPopAdapter(this, mListSource)
        popWindowSource.setAdapter(adapterSource)
        popWindowSource.anchorView = mDatabind.llPigeonSource//设置ListPopupWindow的锚点，关联mButton位置
        popWindowSource.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowSource.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowSource.isModal = true
        popWindowSource.show()
        adapterSource!!.setCheckItem(mPositionSource)
    }

    private fun setPgBloodList(it: PgBloodResponse?) {
        mListBlood.clear()
        mListBlood.add(0, getString(R.string.Add_a_custom))
        if (it != null && it.list.isNotEmpty()) {
            bloodList.clear()
            bloodList.addAll(it.list)
            it.list.forEach {
                mListBlood.add(it.blood)
            }
        }
        adapterBlood = AddBloodPigeonPopAdapter(this, mListBlood)
        popWindowBlood.setAdapter(adapterBlood)
        popWindowBlood.anchorView = mDatabind.llPigeonBlood//设置ListPopupWindow的锚点，关联mButton位置
        popWindowBlood.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowBlood.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowBlood.isModal = true
        popWindowBlood.show()
        adapterBlood!!.setCheckItem(mPositionBlood)
    }

    private fun showInputCustomDialog() {
        val dialog = RxInputCustomDialog(this)
        dialog.setHintText(getString(R.string.max_number_of_12_letters))
        dialog.setEnglishFilter()
        dialog.setTransInformation()
        dialog.setTitle(getString(R.string.Please_select_a_country))
        dialog.setSureListener {
            val customCountry = dialog.getContent()
            if (customCountry.isEmpty()) {
                RxToast.warning(getString(R.string.Please_select_a_country))
                return@setSureListener
            }
            mDatabind.tvCountryNameEn.text = customCountry
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun setPgEyeList(it: PgEyeResponse?) {
        mListEye.clear()
        mListEye.add(0, getString(R.string.Add_a_custom))
        if (it != null && it.list.isNotEmpty()) {
            eyeList.clear()
            eyeList.addAll(it.list)
            it.list.forEach {
                mListEye.add(it.eye)
            }
        }
        adapterEye = AddBloodPigeonPopAdapter(this, mListEye)
        popWindowEye.setAdapter(adapterEye)
        popWindowEye.anchorView = mDatabind.llPigeonEyeSand//设置ListPopupWindow的锚点，关联mButton位置
        popWindowEye.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowEye.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowEye.isModal = true
        popWindowEye.show()
        adapterEye!!.setCheckItem(mPositionEye)
    }

    private fun setFeatherColorList(it: PgFeatherColorResponse?) {
        mColorList.clear()
        mColorList.add(0, getString(R.string.Add_a_custom))
        if (it != null && it.list.isNotEmpty()) {
            colorList.clear()
            colorList.addAll(it.list)
            it.list.forEach {
                mColorList.add(it.featherColor)
            }
        }
        adapterColor = AddBloodPigeonPopAdapter(this, mColorList)
        popWindowColor.setAdapter(adapterColor)
        popWindowColor.anchorView = mDatabind.llPigeonFeatherColor//设置ListPopupWindow的锚点，关联mButton位置
        popWindowColor.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowColor.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowColor.isModal = true
        popWindowColor.show()
        adapterColor!!.setCheckItem(mColorPosition)
    }

    private fun chooseDate() {
        val displayList: MutableList<Int> = mutableListOf()
        displayList.add(DateTimeConfig.YEAR)
        displayList.add(DateTimeConfig.MONTH)
        displayList.add(DateTimeConfig.DAY)
        val dialog = CardDatePickerDialog.builder(this)
            .setTitle(getString(R.string.option_date))
            .setDisplayType(displayList)
            .setBackGroundModel(CardDatePickerDialog.STACK)
            .showBackNow(false)//是否显示一键回到今日 和 定位到今天的日期
            .setPickerLayout(0)
            .setTouchHideable(true)
            .setChooseDateModel(DateTimeConfig.DATE_LUNAR)
            .setWrapSelectorWheel(false)
            .setThemeColor(Color.parseColor("#FF8000"))
            .showDateLabel(false)
            .showFocusDateInfo(false)
            .setOnChoose(getString(R.string.shop_choose)) {
                mDatabind.tvPigeonBirthday.text = DatetimeUtil.conversionTime(it, "yyyy年MM月dd日")
            }
            .setOnCancel(getString(R.string.closed)) {
            }.build()

        dialog.show()
        /**
         * 重点 需要在dialog show 方法后
         * 得到 BottomSheetDialog 实体，设置其 isHideable 为 false
         */
        (dialog as BottomSheetDialog).behavior.isHideable = false
    }

    private fun setCategoryList(it: BreedCategoryResponse?) {
        mCategoryList.clear()
        if (it != null && it.list.isNotEmpty()) {
            categoryList.clear()
            categoryList.addAll(it.list)
            it.list.forEach {
                mCategoryList.add(it.category)
            }
        }
        adapterCategory = AddBloodPigeonPopAdapter(this, mCategoryList)
        popWindowCategory.setAdapter(adapterCategory)
        popWindowCategory.anchorView = mDatabind.llPigeonCategory//设置ListPopupWindow的锚点，关联mButton位置
        popWindowCategory.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowCategory.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowCategory.isModal = true
        popWindowCategory.show()
        adapterCategory!!.setCheckItem(mCategoryPosition)
    }

    private fun setBreedStatusList(it: BreedStatusResponse?) {
        mStatusList.clear()
        if (it != null && it.list.isNotEmpty()) {
            statusList.clear()
            statusList.addAll(it.list)
            it.list.forEach {
                mStatusList.add(it.state)
            }
        }
        adapterStatus = AddBloodPigeonPopAdapter(this, mStatusList)
        popWindowStatus.setAdapter(adapterStatus)
        popWindowStatus.anchorView = mDatabind.llPigeonStatus//设置ListPopupWindow的锚点，关联mButton位置
        popWindowStatus.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowStatus.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowStatus.isModal = true
        popWindowStatus.show()
        adapterStatus!!.setCheckItem(mStatusPosition)
    }

    private fun setYearPopList() {
        mYearList.clear()
        val mList = getYearsFrom1980ToNextYear()
        mYearList = mList.reversed().toMutableList()
        adapterYear = AddBloodPigeonPopAdapter(this, mYearList)
        popWindowYear.setAdapter(adapterYear)
        popWindowYear.anchorView = mDatabind.llYear//设置ListPopupWindow的锚点，关联mButton位置
        popWindowYear.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowYear.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowYear.isModal = true
        popWindowYear.show()
        adapterYear!!.setCheckItem(mYearPosition)
    }

    private fun getYearsFrom1980ToNextYear(): MutableList<String> {
        val currentYear = Calendar.getInstance().get(Calendar.YEAR)
        return (1980..currentYear + 1).map { it.toString() }.toMutableList()
    }

    private fun setCountryList(it: BloodLineDictionaryResponse?) {
        mCountryList.clear()
        if (it != null && it.list.isNotEmpty()) {
            countryList.clear()
            countryList.addAll(it.list)
            it.list.forEach {
                mCountryList.add(it.data + " " + it.name)
            }
            mCountryList.add(0, getString(R.string.hint_unknown))
            mCountryList.add(1, getString(R.string.custom))
        }
        /** 初始化ListPopupWindow，适配 */
        adapterCountry = AddBloodPigeonPopAdapter(this, mCountryList)
        popWindowCountry.setAdapter(adapterCountry)
        popWindowCountry.anchorView = mDatabind.llCountryNameEn//设置ListPopupWindow的锚点，关联mButton位置
        popWindowCountry.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowCountry.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowCountry.isModal = true
        popWindowCountry.show()
        adapterCountry!!.setCheckItem(mPositionCountry)
    }

    private fun selectedPigeonSex(type: String) {
        val isSelect = true
        when (type) {
            "male" -> {
                pigeonSex = getString(R.string.hint_male)
                mDatabind.llMale.isSelected = isSelect
                mDatabind.tvUnKnow.isSelected = !isSelect
                mDatabind.llFemale.isSelected = !isSelect
            }

            "female" -> {
                pigeonSex = getString(R.string.hint_female)
                mDatabind.llMale.isSelected = !isSelect
                mDatabind.tvUnKnow.isSelected = !isSelect
                mDatabind.llFemale.isSelected = isSelect
            }

            "unKnow" -> {
                pigeonSex = getString(R.string.hint_unknown)
                mDatabind.llMale.isSelected = !isSelect
                mDatabind.tvUnKnow.isSelected = isSelect
                mDatabind.llFemale.isSelected = !isSelect
            }
        }
    }
}